package com.simple.card.controller;

import com.simple.card.Utils.AesUtil;
import com.simple.card.Utils.ResultVOUtil;
import com.simple.card.VO.ResultUserInfoVO;
import com.simple.card.VO.ResultVO;
import com.simple.card.annotation.LoginCheck;
import com.simple.card.annotation.SignCheck;
import com.simple.card.dto.KaBaoUserDTO;
import com.simple.card.enums.ResultEnum;
import com.simple.card.exception.CreditException;
import com.simple.card.form.UserLoginForm;
import com.simple.card.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping(value = "/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping(value = "/login")
    @SignCheck(sign = false)
    public ResultVO login(@Valid UserLoginForm userLoginForm,
                          BindingResult bindingResult) {
        if(bindingResult.hasErrors()) {
            log.error("[用户登录] 参数不正确,userLoginForm={}", userLoginForm.toString());
            throw new CreditException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
        Map<String,String> map = userService.login(userLoginForm);
        return ResultVOUtil.success(map);
    }

    @GetMapping("/info")
    @SignCheck(sign = false)
    @LoginCheck(login = true)
    public ResultVO getUserInfo(HttpServletRequest request) {
        String token = AesUtil.decryptData(request.getHeader("Access-User-Token"));
        KaBaoUserDTO kaBaoUserDTO = userService.findDTOByToken(token);
        ResultUserInfoVO resultUserInfoVO = new ResultUserInfoVO();
        resultUserInfoVO.setKaBaoUserDTO(kaBaoUserDTO);
        return ResultVOUtil.success(resultUserInfoVO);
    }
}